<template>
  <div class="account-sequrity">
    <div id="accountForm">
      <base-form :formState="formState" @resetTextarea="resetTextarea" ref="getbaseForm">
      </base-form>
    </div>

    <div class="table-bottom_fiexd" :style="styleWidth">
      <a-button type="primary" :disabled="btnPerm" @click="saveButton">保存</a-button>
    </div>
  </div>
</template>
      

<script lang="ts" setup>
import { ref, reactive, watch, onMounted, nextTick } from "vue";
import { dataSourceType, detailDataItemType } from "@/type.d";
import { accountSafeForm } from './formCofig';
import { cloneDeep } from 'lodash';
import baseForm from '@/components/form/baseForm.vue';
import request from "@/api/index";
import { message } from "ant-design-vue";
import { useFixeWidth, styleWidth } from '@/hooks/useFixeWidth';
import { routerPerm } from '@/utils/common';

// props

// data
const userSecurityInfo = ref<detailDataItemType>([])
const formState = ref<(dataSourceType)[]>(cloneDeep(accountSafeForm));
const methods = ref([]);
const getbaseForm = ref();
const btnPerm = ref<boolean>(false)
//watch
watch(() => userSecurityInfo.value[0], (newVal: any, oldVal) => {
  if (!newVal) {
    formState.value = cloneDeep(accountSafeForm);
    return;
  }
  if (JSON.stringify(newVal)) {
    formState.value.forEach((item) => {
      if (newVal.hasOwnProperty(item.id)) {

        item.children.forEach((data: dataSourceType) => {
          if (newVal[item.id]?.hasOwnProperty(data.param)) {

            if (data.value instanceof Array) {
              data.value = [];
              if (data.picIdPram) { // 图片格式
                let obj = {
                  uid: newVal[item.id][data.picIdPram],
                  url: newVal[item.id][data.param]
                }
                data.value.push(obj)
                data.picId = newVal[item.id][data.picIdPram];
              } else { // 多选格式
                newVal[item.id][data.param] && newVal[item.id][data.param] instanceof Array ?
                  data.value = newVal[item.id][data.param] : data.value.push(newVal[item.id][data.param]);
              }
            } else {
              if (data.param === 'smsVerificationCodeLength') {
                data.optionsValue = newVal[item.id][data.param] == 4 ? 1 : newVal[item.id][data.param] == 6 ? 2 : 3

                data.value = newVal[item.id][data.param] == 8 ? 3 : newVal[item.id][data.param] == 6 ? 2 : 1

              } else if (data.param === 'pwdEncodeType') {
                let index = methods.value.findIndex(val => val === newVal[item.id][data.param])
                data.value = index + 1
                data.options = methods.value
              } else if (data.param === 'blacklist') {
                if (!data.value || !newVal[item.id].enableWeakPwdCheck) {
                  data.value = (newVal[item.id]['blacklist'].join(',')).replace(/,/g, '\n');
                }
              } else {
                data.value = newVal[item.id][data.param] != null ? newVal[item.id][data.param] : '';
              }
            }
            if (data.hasOwnProperty("optionsValue") && newVal[item.id].hasOwnProperty(data.params_options)) {
              data.optionsValue = newVal[item.id][data.params_options];
            }
          } else if (newVal[item.id]?.hasOwnProperty(data.param1) || newVal[item.id]?.hasOwnProperty(data.param2)) {
            data.minValue = newVal[item.id][data.param1] != null ? newVal[item.id][data.param1] : '';
            data.maxValue = newVal[item.id][data.param2] != null ? newVal[item.id][data.param2] : '';
          }
        })
      }
    });
  }
})
watch(() => formState.value, (newVal: any, oldVal) => {
  if (newVal) {
    newVal.forEach((item: any) => {
      if (item.children[0].param1 || item.children[0].param2) {
        item.children[0].maxValue = item.children[0].maxValue < item.children[0].minValue ? item.children[0].minValue : item.children[0].maxValue
      }
    })
  }
  // formState.value = newVal
}, { deep: true })
//methods
const getUserSecurity = async () => {
  request.fetchUserSecurity({}).then((res: dataSourceType | null) => {
    userSecurityInfo.value = [];
    userSecurityInfo.value.push(res);
  });
}
const fetchUserSecuritypwdEncodeMothed = async () => {
  request.fetchUserSecuritypwdEncodeMothed({}).then((res: any) => {
    methods.value = res
    getUserSecurity()
  });
}

// 获取已设置的站点最新的基础信息和扩展信息
const setNewValue = () => {
  const accountSafeNewValue: dataSourceType = {}
  formState.value.forEach((item: dataSourceType) => {
    accountSafeNewValue[item.id] = {};
    item.children.forEach((data: dataSourceType) => {
      if (data.hasOwnProperty('param')) {
        if(data['param'] == 'disableAccoutTime' || data['param'] == 'pwdErrorCountResetPeriod') {
          accountSafeNewValue[item.id][data.param] = data.value === "" ? null : data.value;
        }
        if (data.hasOwnProperty('params_options')) {
          accountSafeNewValue[item.id][data.params_options] = data.optionsValue || null;
        } else if (data.param == 'pwdEncodeType') {
          if (typeof data.value === 'string') {
            accountSafeNewValue[item.id][data.param] = ''
          } else {
            accountSafeNewValue[item.id][data.param] = data.options[data.value - 1]
          }

        } else if (data.param == 'smsVerificationCodeLength') {
          if (typeof data.value === 'number') {
            accountSafeNewValue[item.id][data.param] = data.value === 1 ? 4 : data.value === 2 ? 6 : 8
          }
        } else {
          accountSafeNewValue[item.id][data.param] = data.value === "" ? null : data.value;
          if (data.param == 'blacklist') {
            accountSafeNewValue[item.id][data.param] = [];
            accountSafeNewValue[item.id][data.param] = data.value.split('\n');

          }
        }
      } else if (data.hasOwnProperty('param1') || data.hasOwnProperty('param2')) {
        accountSafeNewValue[item.id][data.param1] = data.minValue === "" ? null : data.minValue;
        accountSafeNewValue[item.id][data.param2] = data.maxValue === "" ? null : data.maxValue;
      }
    })
  })
  return accountSafeNewValue
}
//重置弱密码库
const resetTextarea = (item: any, section_index: number, item_index: number) => {
  let weakList: any[] = [];
  request.weakPwdList({}).then((res: any) => {
    weakList = res.map((item: any) => item.weakPwd);
    formState.value[section_index].children[item_index].value = weakList.join(',').replace(/,/g, '\n');
  });


}
//保存数据
const saveButton = async () => {
  const accountSafeNewValue = setNewValue();
  console.log(accountSafeNewValue, 'accountSafeNewValue')
  let accountSafeForm = getbaseForm.value.baseForm;
  accountSafeForm.validate()
    .then(() => {
      request.fetchUserSecurityUpdate(accountSafeNewValue).then((res: dataSourceType) => {
        if (res.code == '00000 00000') {
          message.success(res.message);
          getUserSecurity();
        } else {
          message.error(res.message)
        }
      })
    }).catch((err: any) => {
      throw new Error(err);
    });
}

//onMounted
onMounted(() => {
  routerPerm().includes('saveAble') ? btnPerm.value = false : btnPerm.value = true
  fetchUserSecuritypwdEncodeMothed()
  useFixeWidth();
})
</script>
<style lang="less" scoped>
.account-sequrity {
  padding-left: 16px;
  height: 100%;
  background-color: #fff;
  width: 100%;
  height: calc(100% - 120px);
  padding-bottom: 56px;

  #accountForm {
    height: 100%;
    overflow-y: auto;

  }

  .table-bottom_fiexd {
    height: 48px;
    display: flex;
    justify-content: center;
    align-items: center;
    position: fixed;
    bottom: 0;
    background: #fff;
  }
}
</style>
<style lang="less">
#accountForm {
  .form-a-radio-group_associated {
    display: flex;
    margin-left: 290px;
    margin-top: 16px;
  }

  .ant-form-item-label {
    text-align: right;
    width: 295px;
    margin-right: 8px;
  }
}
</style>
